<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="logo上传" prop="logo">
        <image-upload v-model="form.logo" />
      </el-form-item>
      <el-form-item label="核准日期" prop="checkDate">
        <el-date-picker
          style="width: 30%"
          clearable
          v-model="form.checkDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择核准日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="修改日期" prop="mixDate">
        <el-date-picker
          style="width: 30%"
          clearable
          v-model="form.mixDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择药品修改时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="色彩" prop="colorType">
        <el-select
          clearable
          v-model="form.colorType"
          placeholder="请选择色彩"
          style="width: 30%"
        >
          <el-option :value="1" label="彩色">彩色</el-option>
          <el-option :value="2" label="黑白">黑白</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="药品名称" prop="medicineCnName">
        <el-input
          style="width: 30%; display: block"
          v-model="form.medicineCnName"
          placeholder="请输入药品名称"
        />
        <el-input
          style="width: 30%"
          disabled
          placeholder="请在医生指导下使用"
        />
      </el-form-item>
      <el-form-item label="底部编码" prop="bottomCoding">
        <el-input
          style="width: 30%; display: block"
          v-model="form.bottomCoding"
          placeholder="请输入底部编码"
        />
      </el-form-item>
    </el-form>
    <div class="header">
      <h3 style="font-weight: bold">新增说明书详情</h3>
      <el-button type="success" plain @click="handleUpdate"
        >新增下一段</el-button
      >
    </div>
    <audio id="audioPlayer" controls style="display: none"></audio>
    <el-table
      ref="el-table"
      :data="tableData"
      row-key="FWBcontent"
      style="width: 100%"
    >
      <!-- 表格列定义 -->
      <el-table-column prop="title" label="段落名称" width="180">
        <template slot-scope="scope">
          <div>【{{ scope.row.title }}】</div>
        </template>
      </el-table-column>
      <el-table-column prop="content1" label="段落内容"></el-table-column>
      <el-table-column fixed="right" label="操作" width="220">
        <template slot-scope="scope">
          <!-- @click.native.prevent="" -->
          <el-button
            icon="el-icon-mic"
            @click="audition(scope.$index, tableData)"
            type="text"
            size="small"
          >
            试听
          </el-button>
          <el-button
            icon="el-icon-edit"
            @click.native.prevent="editeRow(scope.$index, tableData)"
            type="text"
            size="small"
          >
            编辑
          </el-button>
          <el-button
            icon="el-icon-delete"
            @click.native.prevent="deleteRow(scope.$index, tableData)"
            type="text"
            size="small"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 20px">
      段落标题：<el-input
        style="width: 30%"
        v-model="title"
        placeholder="请输入段落标题"
      />
    </div>

    <div style="margin-top: 20px">
      字号： <el-radio v-model="isBold" :label="2">加粗</el-radio>
      <el-radio v-model="isBold" :label="1">不加粗</el-radio>
    </div>

    <div style="margin-top: 20px">
      <editor v-model="FWBcontent" :min-height="192" />
      <!-- <span style="font-size: 12px;color: #ff000069;">注：【】里为段落名称</span> -->
    </div>
    <div class="header">
      <div></div>
      <el-button type="primary" @click="getContent" :loading="loading"
        >确认并生成语音</el-button
      >
    </div>
    <div class="footer">
      <el-button class="button" type="primary" @click="submitForm"
        >发布</el-button
      >
      <el-button class="button" type="primary" @click="blankNew"
        >预览</el-button
      >

      <!-- <el-button class="button" type="primary" @click="getAudio">播放</el-button> -->
    </div>
  </div>
</template>

<!-- <script src="./tts-demo/example/base64.js"></script>
<script src="./tts-demo/example/crypto-js.js"></script>
<script src="./tts-demo/dist/index.umd.js"></script>
<script src="./tts-demo/example/tts/index.js"></script> -->

<script>
import {
  listMeidicineInfo,
  textToAudio,
  getMeidicineInfo,
  delMeidicineInfo,
  addMeidicineInfo,
  updateMeidicineInfo,
} from "@/api/system/instructions";

import { set } from "nprogress";

import Sortable from "sortablejs";
// import { Table } from 'antd';
export default {
  name: "instructions",
  data() {
    return {
      form: {
        logo: null,
        checkDate: null,
        mixDate: null,
        medicineCnName: null,
        colorType: 1,
      },
      loading: false,
      // checkboxList: 1,
      tableData: [],
      audioObj: {},
      // 表单校验
      rules: {
        logo: [{ required: true, trigger: "blur", message: "请上传logo" }],
        checkDate: [
          { required: true, trigger: "blur", message: "请选择核准日期" },
        ],
        // mixDate: [
        //   { required: true, trigger: "blur", message: "请选择修改日期" }
        // ],
        medicineCnName: [
          { required: true, trigger: "blur", message: "请输入药品名称" },
        ],
        colorType: [{ required: true, trigger: "blur", message: "请选择色彩" }],
      },
      FWBcontent: "",
      index: 0,
      title: "",
      audioindex: 0,
      isBold: 1,
    };
  },
  created() {
    if (this.$route.query.id) {
      this.handleGetMeidicineInfo(this.$route.query.id);
    } else {
      this.form = {
        medicineCnName: this.$route.query.medicineCnName,
        medicineSpecifications: this.$route.query.medicineSpecifications,
        colorType: 1,
      };
    }
  },
  mounted() {
    this.audioObj = new Audio(); //在VUE中使用audio标签
    this.initSort();
  },
  methods: {
    getAudio() {
      let formData = new FormData();
      formData.append("auditText", "1111111");
      textToAudio(formData)
        .then((response) => {
          //    console.log(response);
          //alert(11);
          // let url = URL.createObjectURL(response)//通过这个API让语音数据转为成一个url地址
          // this.audioObj.src = url//设置audio的src为上面生成的url
          // let playPromiser = this.audioObj.play()//进行播
          //  audio.src = 'https://dycrm.fanshucar.cn/prod-api/profile/music/11.mp3'; // 更换为你的音频文件路径
          var voiceUrl =
            process.env.VUE_APP_BASE_API + "/profile/upload/" + response.msg;
          // audio.src = voiceUrl;
          alert(voiceUrl);

          //           document.getElementById('audioPlayer').src = voiceUrl;
          // // 播放音频
          //            document.getElementById('audioPlayer').play();
          //          //  audio.play();
          //           //在谷歌内核中,audio.play()会返回一个promise的值，在IE内核中就不会返回任何的值
          //           //所以如果你要分浏览器，可以判断playPromiser的值来进行操作哦
          //           this.audioObj.onended = () => { }
          //           this.audioLoading = false
        })
        .catch((err) => {});
    },
    handleGetMeidicineInfo(id) {
      this.tableData = [];
      getMeidicineInfo(id).then((response) => {
        this.form = response.data;
        let withoutTag = "";
        this.form.medicineDetails.map((el) => {
          if (/<[^>]+>/.test(el.content)) {
            withoutTag = el.content.replace(/<[^>]+>/g, "");
          } else {
            withoutTag = el.content;
          }
          this.tableData.push({
            title: el.title,
            isBold: el.isBold,
            content: withoutTag,
            FWBcontent: el.content,
            voiceUrl: el.voiceUrl,
            edit: false,
          });

          this.tableData.forEach((element) => {
            if (element.content) {
              element.content1 = element.content.replace(/&nbsp/g, "");
            }
          });
        });
        console.log(this.form, "this.form");
      });
    },
    handleUpdate() {
      this.FWBcontent = "";
      this.tableData.map((el) => {
        el.edit = false;
      });
    },
    initSort() {
      const el = this.$refs["el-table"].$el.querySelector(
        ".el-table__body-wrapper > table > tbody"
      );
      let _this = this;
      const ops = {
        animation: 200, //动画时长
        ghostClass: "ghostClass", //设置拖拽停靠样式类名
        handle: ".el-table__row", //可拖拽区域class
        //拖拽中事件
        onMove: ({ dragged, related }) => {
          const oldRow = _this.tableData[dragged.rowIndex]; //旧位置数据
          const newRow = _this.tableData[related.rowIndex]; //被拖拽的新数据
        },
        //拖拽结束事件
        onEnd: (evt) => {
          const curRow = _this.tableData.splice(evt.oldIndex, 1)[0];
          _this.tableData.splice(evt.newIndex, 0, curRow);
        },
      };
      Sortable.create(el, ops);
    },

    getContent() {
      this.loading = true;
      if (!this.title || !this.FWBcontent) {
        this.$message("请输入名称或内容");
        return;
      }

      //去掉标签
      const withoutTags = this.FWBcontent.replace(/<[^>]+>/g, ""); // 去除所有<p>和</p>标签
      const secondFieldPattern = /】([\s\S]*?)(?=<\/p>|$)/; // 使用正向肯定预查(?=...)来确保后面紧跟的是</p>或字符串结尾
      const secondFieldMatch = withoutTags.match(secondFieldPattern);
      let secondField = "";
      if (secondFieldMatch) {
        secondField = secondFieldMatch ? secondFieldMatch[1].trim() : "";
      } else {
        secondField = withoutTags;
      }
      console.log(secondField, "secondField",this.FWBcontent);
      
      let formData = new FormData();
      formData.append("auditText", `${this.title},${secondField}`);
      //判断编辑
      const aa = this.tableData.some((el) => el.edit == true);
      if (aa) {
        textToAudio(formData)
          .then((response) => {
            this.tableData[this.index].title = this.title;
            this.tableData[this.index].isBold = this.isBold;
            this.tableData[this.index].content1 = secondField;
            this.tableData[this.index].FWBcontent = this.FWBcontent;
            this.tableData[this.index].edit = false;
            this.tableData[this.index].voiceUrl = response.msg;
            this.loading = false;
            setTimeout(() => {
              this.FWBcontent = "";
              this.title = "";
            }, 2000);
          })
          .catch((err) => {});
      } else {
        textToAudio(formData)
          .then((response) => {
            this.tableData.push({
              title: this.title,
              isBold: this.isBold,
              content1: secondField,
              FWBcontent: this.FWBcontent,
              edit: false,
              voiceUrl: response.msg,
            });
            this.loading = false;
            setTimeout(() => {
              this.FWBcontent = "";
              this.title = "";
            }, 2000);
          })
          .catch((err) => {});
      }
      console.log(this.tableData);
    },
    //编辑
    editeRow(i, arr) {
      this.FWBcontent = arr[i].FWBcontent;
      this.title = arr[i].title;
      this.isBold = arr[i].isBold;
      this.tableData[i].edit = true;
      this.index = i;
    },
    // audition(i, arr) {
    //   fetch("https://tsn.baidu.com/text2audio?tok=" + "24.ee8ce38fc0723287ab1b28f1a29e8b3a.2592000.1736909688.282335-116670895" +
    //     "&tex=" + arr[i].content +
    //     "&cuid=MQtX1eobGiuaFK4rbomQRDs8jHcvnms1&ctp=1&lan=zh&spd=5&pit=5&vol=5" +
    //     "&per=0" +
    //     "&aue=3")
    //     .then(response => response.blob()) // 将响应转换为Blob
    //     .then(blob => {
    //       // 创建一个URL表示此blob对象
    //       const blobUrl = URL.createObjectURL(blob);
    //       // 设置audio元素的src属性为新创建的URL
    //       document.getElementById('audioPlayer').src = blobUrl;
    //       // 播放音频
    //       document.getElementById('audioPlayer').play();
    //     });
    // },
    audition(i, arr) {
      if (!arr[i].voiceUrl) {
        this.$message.error("暂无语音文件,请先生成语音");
        return;
      } else {
        var voiceUrl =
          process.env.VUE_APP_BASE_API + "/profile/upload/" + arr[i].voiceUrl;
        this.pauseAudio(voiceUrl, i);
      }
    },
    // 暂停/播放
    pauseAudio(voiceUrl, i) {
      console.log(i, this.audioindex, voiceUrl);
      var audioPlayer = document.getElementById("audioPlayer");
      if (i == this.audioindex) {
        // console.log('执行11111');

        if (audioPlayer.paused || audioPlayer.ended) {
          // console.log('执行22222');

          document.getElementById("audioPlayer").src = voiceUrl;
          audioPlayer.play();
        } else {
          // console.log('执行33333');

          audioPlayer.pause();
        }
      } else {
        // console.log('执行44444');

        document.getElementById("audioPlayer").src = voiceUrl;
        audioPlayer.play();
        this.audioindex = i;
      }
    },
    //删除
    deleteRow(i) {
      this.tableData.splice(i, 1);
    },
    submitForm() {
      this.$modal.loading("保存中");
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.tableData.length > 0) {
            let newData = this.tableData.map((item) => ({
              title: item.title,
              isBold: item.isBold,
              content: item.FWBcontent,
              voiceUrl: item.voiceUrl,
            }));
            this.form.medicineDetails = newData;

            if (this.form.id != null) {
              updateMeidicineInfo(this.form).then((response) => {
                this.$modal.msgSuccess("修改发布成功");
                this.$modal.closeLoading();
                this.$router.go(-1);
              });
            } else {
              addMeidicineInfo(this.form).then((res) => {
                if (res.code == 200) {
                  this.$modal.msgSuccess("发布成功");
                  this.$modal.closeLoading();
                  this.$router.go(-1);
                }
              });
            }
          } else {
            this.$message("请输入必填内容后再点击发布");
            this.$modal.closeLoading();
          }
        } else {
          this.$message("请输入必填内容后再点击发布");
          this.$modal.closeLoading();
        }
      });
    },
    blankNew() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.tableData.length > 0) {
            this.NewHtml();
          } else {
            this.$message("请输入必填内容后再点击预览");
          }
        }
      });
    },
    NewHtml() {
      const itemList = this.tableData
        .map(
          (item) => `
      <div class="content">
        <div class="content-flex">
          <div class="content-title">【${item.title}】</div>

          <button onclick="handleSpeak('${item.content}')">
            <img
              class="content-img"
              src="https://rb.biomedical-wh.com/prod-api//profile/bdm_img/broadcast.png"
              alt=""
            />
          </button>
        </div>
      <div class="content-info">${item.FWBcontent}</div>
      </div>
  `
        )
        .join("");
      console.log(this.tableData);

      //logo
      const image = this.form.logo.split(",");

      const imageList = image
        .map(
          (imageUrl) =>
            `<img src="${
              "http://121.41.46.17:8088/prod-api" + imageUrl
            }" alt='' style="margin:10px;width:120px;"/>`
        )
        .join("");

      let btn;
      if (this.form.colorType == 1) {
        btn = `<div class="btn btnImg">活血化瘀 通脉活络</div>`;
      } else {
        btn = `<div class="btn btnColor">活血化瘀 通脉活络</div>`;
      }
      var htmlContent = `
      <html>
      <meta charset="UTF-8">
      <body>
        <div id="image-container">${imageList}</div>
        <div class="page">
          <div class="title">${this.form.medicineCnName}</div>
          <div class="title1">请仔细阅读说明书并在医师指导下使用</div>
          <div style="width:100%;height:100%;">${btn}</div>
          <div style="width:100%;height:100%;">${itemList}</div>
        </div>
      <style>
        #image-container {
          display: flex;
          align-items: center;
        }

        .speaker {
          width: 100%;
          display: flex;
          justify-content: flex-end;
        }

        .input{
          width: 50%;
          height: 45px;
          font-size: 25px;
        }
        .button {
          background: none;
          font-size: 45px;
          margin-top: 20px;
        }

        .page {
          display: flex;
          align-items: center;
          flex-direction: column;
          padding: 20px;
        }

        .body {
          width: 100%;
          height: 100%;
          display: flex;
          align-items: center;
          flex-direction: column;
        }

        .title {
          width: 100%;
          text-align: center;
          font-size: 60px;
          font-weight: bold;
        }

        .title1 {
          font-size: 40px;
          width: 70%;
          text-align: center;
          font-weight: 600;
          margin-top: 20px;
        }
        .btnColor{
          background: #eef0f1;
          color: #000;

        }
        .btnImg{
          background: url('https://rb.biomedical-wh.com/prod-api//profile/bdm_img/不带字.png') no-repeat;
          background-size: 100% 100%;
          color: #fff;
        }

        .btn {
          width: 100%;
          height: 90px;
          border-radius: 8px;
          display: flex;
          justify-content: center;
          font-size: 40px;
          margin-top: 30px;
          font-weight: 400;
          align-items: center;
        }

        .content {
          width: 100%;
          padding: 0 30px;
          margin-top: 30px;
        }

        .content-img {
          width: 45px;
          height: 45px;
        }

        .content-flex {
          display: flex;
          justify-content: space-between;
          align-items: center;
        }

        .content-title {
          font-weight: 500;
          font-size: 45px;
          margin: 10px 0;
        }

        .content-info {
          font-size: 26px;
          margin: 10px 0;
          color: #7e7d7d;
        }

        #slider-container {
          width: calc(100% - 400px);
          text-align: center;
        }

        #slider {
          width: 100%;
          margin-top: 20px;
        }

        #value {
          font-size: 24px;
          margin-top: 20px;
        }

        .flex {
          width: 100%;
          position: fixed;
          bottom: 0;
          display: flex;
          justify-content: center;
          align-items: center;
          font-size: 42px;
          background: #fff;
          height: 140px;
        }
      </style>
</body>

</html>
`;
      var blob = new Blob([htmlContent], { type: "text/html" });
      var url = URL.createObjectURL(blob);
      window.open(url, "_blank");

      // 完成后释放 URL 对象（可选，但推荐）
      URL.revokeObjectURL(url);
    },
  },
};
</script>
<style scoped>
.header {
  width: 100%;
  height: 70px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.ghostClass {
  background-color: pink;
}

.footer {
  width: 100%;
  height: 70px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
